package top.hkyzf.study.j2se.juc;

import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.CopyOnWriteArraySet;

/**
 * 集合类不安全的问题
 * @author 朱峰
 * @date 2020-12-24 13:01
 */
public class ContainerNotSafeDemo {
    public static void main(String[] args) {
        // 线程不安全
        // List<String> list = new ArrayList<>();
        // Set<String> set = new HashSet<>();
        // Map<String, Object> map = new HashMap<>();

        // 解决方式 1
        // List<String> list = new Vector<>();

        // 解决方式 2
        // List<String> list = Collections.synchronizedList(new ArrayList<>());
        // Set<String> set = Collections.synchronizedSet(new HashSet<>());
        // Map<String, Object> map = Collections.synchronizedMap(new HashMap<>());

        // 解决方式 3 写时复制
        List<String> list = new CopyOnWriteArrayList<>();
        Set<String> set = new CopyOnWriteArraySet<>();
        Map<String, Object> map = new ConcurrentHashMap<>();

        for (int i = 0; i < 10; i++) {
            new Thread(() -> {
                list.add("list:" + UUID.randomUUID().toString().substring(0, 8));
                System.out.println(list);
                set.add("set:" + UUID.randomUUID().toString().substring(0, 8));
                System.out.println(set);
                map.put("map:" + UUID.randomUUID().toString().substring(0, 8), UUID.randomUUID().toString().substring(0, 8));
                System.out.println(map);
            }, String.valueOf(i)).start();
        }
        new HashSet<>().add("1");
    }
}
